import { provide, inject, ref, unref } from 'vue'
import { message as Message } from 'ant-design-vue'
import { debounce } from 'lodash-es'
import { nanoid } from 'nanoid'
import { userList } from '@/api/user.js'
import { getAuditList } from '@/api/audit.js'
import dayjs from 'dayjs'
/**
 * Symbol
 */
export const columnsSymbol = Symbol('columns')
export const dataSourceSymbol = Symbol('dataSource')
export const querySymbol = Symbol('query')
export const lineheightSymbol = Symbol('lineheight')
export const loadingSymbol = Symbol('loading')
export const rowSelectionSymbol = Symbol('rowSelection')
export const rowSelectionActiveSymbol = Symbol('rowSelectionActive')
export const filtersAuditSymbol = Symbol('filtersAudit')
export const sortAuditSymbol = Symbol('sortAudit')

/**
 * 注册
 */
export function useProvideContextRegistry() {
  let columns = ref([])
  let dataSource = ref([])
  let r = defaultTimeRange()
  let query = ref({
    start: r[0].format(),
    end: r[1].format(),
  })
  let lineheight = ref()
  let loading = ref(false)
  let selectedRowKeys = ref([])
  let rowSelection = {
    selectedRowKeys,
    onChange: keys => {
      selectedRowKeys.value = keys
    },
    getCheckboxProps: record => ({
      disabled: record.isPublished === 1 || record.userStatus === 'resign',
    }),
  }
  let rowSelectionActive = ref(false)
  let filtersAudit = ref()
  let sortAudit = ref()

  provide(columnsSymbol, columns)
  provide(dataSourceSymbol, dataSource)
  provide(querySymbol, query)
  provide(lineheightSymbol, lineheight)
  provide(loadingSymbol, loading)
  provide(rowSelectionSymbol, rowSelection)
  provide(rowSelectionActiveSymbol, rowSelectionActive)
  provide(filtersAuditSymbol, filtersAudit)
  provide(sortAuditSymbol, sortAudit)
}

/**
 * 获取值
 */
export function useColumns() {
  return inject(columnsSymbol)
}
export function useDataSource() {
  return inject(dataSourceSymbol)
}
export function useQuery() {
  return inject(querySymbol)
}
export function useLineheight() {
  return inject(lineheightSymbol)
}
export function useLoading() {
  return inject(loadingSymbol)
}
export function useRowSelection() {
  return inject(rowSelectionSymbol)
}
export function useRowSelectionActive() {
  return inject(rowSelectionActiveSymbol)
}
export function useFiltersAudit() {
  return inject(filtersAuditSymbol)
}
export function useSortAudit() {
  return inject(sortAuditSymbol)
}

/**
 * 默认时间范围
 */

export function defaultTimeRange() {
  return [dayjs().subtract(30 - 1, 'day'), dayjs()]
}

/**
 * 管理工具
 */
export function useDataSourceManager() {
  let dataSource = useDataSource()
  let query = useQuery()
  let loading = useLoading()
  let filtersAudit = useFiltersAudit()
  let sortAudit = useSortAudit()
  let sortJoinTimeType = ref()
  let sortInternEndDateType = ref()
  let filtersUerStatustType = ref()
  let filtersIsPublishedType = ref()
  let sortCreatetimeType = ref()
  let filtersAccessSuccess = ref()
  let filtersUserNameType = ref()
  let filtersOperationModule = ref()

  let update = debounce(async () => {
    loading.value = true
    let { current, pageSize, ...otherQuery } = query.value
    if (filtersAudit.value) {
      // filtersUerStatustType.value =
      //   filtersAudit.value?.userStatus !== null
      //     ? filtersAudit.value?.userStatus[0]
      //     : ''
      // filtersIsPublishedType.value =
      //   filtersAudit.value?.isPublished !== null
      //     ? filtersAudit.value?.isPublished[0]
      //     : ''

      filtersAccessSuccess.value =
        filtersAudit.value?.accessSuccess !== null
          ? filtersAudit.value?.accessSuccess
          : ''
      filtersUserNameType.value =
        filtersAudit.value?.userName !== null
          ? filtersAudit.value?.userName
          : ''
      filtersOperationModule.value =
        filtersAudit.value?.operationModule !== null
          ? filtersAudit.value?.operationModule[0]
          : ''
    }
    if (sortAudit.value) {
      if (sortAudit.value.columnKey === 'createdTime') {
        sortCreatetimeType.value = sortAudit.value.order
      }
    }
    try {
      let result =
        (await getAuditList({
          pageNum: current,
          pageSize,
          keyWord: otherQuery.keyWord,
          startCreatedTime: otherQuery.start,
          endCreatedTime: otherQuery.end,
          operationModuleKey: filtersOperationModule.value || '',
          createdTimeAsc: sortCreatetimeType.value === 'ascend',
          // createTime: (sortCreatetimeType.value || '').replace(/end$/, ''),
          // accessSuccess: filtersAccessSuccessType.value || '',
        })) || {}
      query.value.current = result?.data?.current || current
      query.value.pageSize = result?.data?.pageSize || pageSize
      query.value.total = result?.data?.total || 0
      dataSource.value = result?.data?.records
      loading.value = false
    } catch (e) {
      Message.error('列表加载失败')
      loading.value = false
    }
  }, 300)

  return { update }
}
export function useQueryManager() {
  let query = useQuery()
  return {
    set(newQuery) {
      query.value = unref(newQuery)
    },
    assign(newQuery) {
      query.value = Object.assign({}, query.value, newQuery)
    },
  }
}
